package com.nachuan.pdd.api;

import cn.hutool.json.JSONUtil;
import com.nachuan.pdd.internal.SendMessageUtil;
import com.pdd.pop.sdk.message.WsClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class PddMessageSocket implements CommandLineRunner {

	// 设置最大重试次数和初始等待时间（毫秒）
	private static final int MAX_RETRIES = 5;
	private static final long INITIAL_BACKOFF = 1000; // 初始等待时间为1秒
	@Autowired
	private SendMessageUtil sendMessageUtil;
	@Value("${project.message.push.enable}")
	private boolean enable;
	@Value("${project.message.push.url}")
	private String url;
	// WebSocket客户端实例
	private volatile WsClient wsClient = null;

	@Override
	public void run(String... args) throws Exception {
		if (enable) {
			startConnection();
		}
	}

	private void startConnection() {
		new Thread(() -> {
			while (true) { // 持续尝试连接
				try {
					log.info("拼多多消息服务连接中...");
					wsClient = new WsClient("wss://message-api.pinduoduo.com", "090bb23d91e44e4cbc67f2d4bb29f877", "1e2fcab0fb6143792b6852a9f01670ac1033a2b5", message -> {
						log.info("接受到拼多多消息 == {}", JSONUtil.toJsonStr(message));
						sendMessageUtil.sendMessage(JSONUtil.toJsonStr(message), url);
					});

					if (!wsClient.isOnline()) {
						wsClient.connect();
					}

					if (wsClient.isOnline()) {
						log.info("拼多多消息服务已开启");
						// 进入一个循环来检查连接状态
						while (wsClient.isOnline()) {
							Thread.sleep(5000); // 定期检查连接状态，这里设置为每5秒检查一次
						}
						log.warn("检测到连接断开，准备重连...");
					} else {
						throw new Exception("未能成功连接至拼多多消息服务");
					}
				} catch (Exception e) {
					log.error("连接失败: {}", e.getMessage());
					tryReconnect();
				}
			}
		}).start();
	}

	private void tryReconnect() {
		int attempt = 0;
		while (attempt < MAX_RETRIES) {
			try {
				long backOffTime = INITIAL_BACKOFF * (long) Math.pow(2, attempt); // 指数退避
				log.warn("将在 {} 毫秒后进行第 {} 次重试...", backOffTime, attempt + 1);
				Thread.sleep(backOffTime);
				log.info("正在尝试重新连接...");
				if (wsClient != null && !wsClient.isOnline()) {
					wsClient.connect(); // 尝试重新连接
				}
				if (wsClient != null && wsClient.isOnline()) {
					log.info("重新连接成功！");
					return; // 成功连接后退出重试循环
				}
				attempt++; // 增加重试计数器
			} catch (InterruptedException e) {
				Thread.currentThread().interrupt();
				log.warn("重连等待期间线程被中断: {}", e.getMessage());
				break;
			} catch (Exception e) {
				log.error("重连失败: {}", e.getMessage());
				attempt++; // 增加重试计数器
			}
		}
		log.error("达到最大重试次数，仍无法连接至拼多多消息服务.");
	}
}